import { computed, defineComponent, ref } from "vue";
import type { IChapter, ICourse, IQuestion } from '@/types'
import { useLocalStor, useStore } from '@/hooks'
import { E_QUESTION } from '@/types'
import { RouterLink, useRoute, useRouter } from "vue-router";
import Card from "@/components/Card";
import styles from './index.module.less'
import { ElButton } from "element-plus";

const QUESTION_MAP: { [key: string]: string } = {
    [E_QUESTION.CHECKBOX]: '单选',
    [E_QUESTION.SELECT]: '判断',
}


export default defineComponent({
    name: 'Detail',
    setup() {
        const { getChapter, getCourse } = useStore()
        const router = useRouter()
        const localStore = useLocalStor()
        const route = useRoute()
        const course = getCourse(route.query.courseId as string)
        const chapter = getChapter(
            route.query.courseId as string,
            route.query.chapterId as string
        )
        const QSIndex = ref(0)
        const currentQuestion = ref<IQuestion>(chapter!.questions[QSIndex.value])
        const localStoreKey = `${course!.title}`

        const ended = computed(() => {
            return QSIndex.value > chapter!.questions.length - 1
        })

        const setNextQuestion = () => {
            QSIndex.value++
            if (ended.value) return
            currentQuestion.value = chapter!.questions[QSIndex.value]
        }

        const saveToLocalStore = (val: string, error: boolean) => {
            let answeredQuestion = []
            if (localStore.get(localStoreKey)) answeredQuestion = localStore.get(localStoreKey)

            answeredQuestion.push({ id: currentQuestion.value.description, error })

            localStore.set(localStoreKey, answeredQuestion)
        }

        const goBack = () => {
            router.push({ path: `/course`, query: { id: course?.title } })
        }

        return () => {
            if (!chapter) return null
            return (
                <>
                    <ElButton onClick={goBack}>回到课程页面</ElButton>
                    <div class={styles.detail}>
                        <div class={styles.detailTitle}>{QUESTION_MAP[currentQuestion.value.type]}</div>
                        {
                            ended.value
                                ? <RouterLink to={`/course?id=${course?.title}`}>回到课程页面</RouterLink>
                                : <Card question={currentQuestion.value} onNext={setNextQuestion} onAnswer={saveToLocalStore}></Card>
                        }
                        <div class={styles.detailPage}>{QSIndex.value + 1}/{chapter.questions.length}</div>
                    </div>
                </>
            )
        }
    }
})